package cn.jja8.config.tool.work.obj.arrays;

import cn.jja8.config.tool.work.obj.ObjKeep;
import cn.jja8.config.tool.work.obj.ObjKeepManager;
import cn.jja8.config.tool.work.obj.common.CommonKeep;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class KeepArrays implements ObjKeep<Object[]> {
    private final ObjKeepManager objKeepManager;
    public KeepArrays(ObjKeepManager objKeepManager) {
        this.objKeepManager = objKeepManager;
    }

    /**
     * 将con转换成自己提供的对象
     * */
    public Object[] in(List con, Class<? extends Object[]> arrayType){
        Class up = arrayType.getComponentType();
        if (Object[].class.isAssignableFrom(up)){
            return con.stream().map(obj->in((List)obj,up)).toArray(value -> Array.newInstance(up,value));
        }
        CommonKeep commonKeep = objKeepManager.getCommonKeepManager().getNoNull(up);
        return con.stream().map(obj->commonKeep.in(obj)).toArray(value -> Array.newInstance(up,value));
    }

    /**
     * 将自己提供的对象转换成con
     * */
    public List out(Object[] v,Class<? extends Object[]> arrayType){
        Class up = arrayType.getComponentType();
        if (Object[].class.isAssignableFrom(up)){
            return (List) Arrays.stream(v).map(mv->out((Object[]) mv,up)).collect(Collectors.toList());
        }
        CommonKeep commonKeep = objKeepManager.getCommonKeepManager().getNoNull(up);
       return Arrays.stream(v).map(mv->commonKeep.out(mv)).collect(Collectors.toList());
    }
}
